<?php
/**
 * Note:     [Description]
 * Author:   longhui.huang <1592328848@qq.com>
 * DateTime: 2024/2/1 12:55
 */
declare(strict_types=1);

namespace App\Service;

use App\Bean\AuthorityBean;
use App\Dao\RoleDao;
use App\Model\UserModel;

class RoleService extends BaseService
{
    /**
     * 根据用户ID查询
     *
     * @param int $userId 用户ID
     *
     * @return array
     */
    public function findByUserId(int $userId)
    {
        /** @var RoleDao $roleDao */
        $roleDao = app(RoleDao::class);
        return $roleDao->findByUserId($userId);
    }

    /**
     * 获取用户权限信息
     *
     * @param UserModel $userModel 用户信息
     */
    public function mapToGrantedAuthorities(UserModel $userModel)
    {
        $permissions = [];

        if ($userModel->isAdmin) {
            $authorityBean = new AuthorityBean(['authority' => 'admin']);
            return [$authorityBean];
        }

        /** @var RoleDao $roleDao */
        $roleDao = app(RoleDao::class);
        $roles   = $roleDao->findByUserId($userModel->userId);
        foreach ($roles as $role) {
            $permissions[] = $role['menu_permission'];
        }

        return array_unique($permissions);
    }
}
